package cn.nexd.app.arsenal.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;

import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import cn.nexd.app.adapter.MyExpandableListAdapter;
import cn.nexd.app.NexdApplication;
import cn.nexd.app.arsenal.R;
import cn.nexd.app.model.ExpandableModel;
import cn.nexd.app.model.MallModel;

/**
 * Created by wangxu on 16/2/24.
 */
public class MallListFragment extends DialogFragment implements AbsListView.OnScrollListener {

    private static final String TAG = "iphone";
    private static final String PRE = "IphoneExpandableListActivity--";
    EditText search;
    ExpandableListView listView;
    FrameLayout indicatorGroup;
    Button commit;
    private ArrayList<ExpandableModel> expandableModels = new ArrayList<ExpandableModel>();
    private ArrayList<ExpandableModel> searchMalls = new ArrayList<ExpandableModel>();
    private MyExpandableListAdapter mAdapter;
    private int indicatorGroupId = -1;
    private int indicatorGroupHeight;

    public interface OnFinishClicked {
        void onFinished(MallModel mallModel);
    }

    private LayoutInflater mInflater;

    private OnFinishClicked onFinishClicked;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        onFinishClicked = (OnFinishClicked) activity;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_choose_malls, container, false);
        this.getDialog().setTitle("选择商场");
        expandableModels = NexdApplication.malls;
        search = (EditText) view.findViewById(R.id.auto_complate);
        listView = (ExpandableListView) view.findViewById(R.id.expandableListView);
        indicatorGroup = (FrameLayout) view.findViewById(R.id.topGroup);
        commit = (Button) view.findViewById(R.id.commit);
        commit.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                onFinishClicked.onFinished(NexdApplication.selectedMallModel);
                MallListFragment.this.getDialog().dismiss();
            }
        });

        // 新加入的
        mInflater = (LayoutInflater) MallListFragment.this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        indicatorGroup.setVisibility(View.INVISIBLE);
        mInflater.inflate(R.layout.list_item, indicatorGroup, true);
        mAdapter = new MyExpandableListAdapter(MallListFragment.this.getActivity(), mInflater);
        mAdapter.addMalls(expandableModels);
        listView.setAdapter(mAdapter);
        listView.setOnScrollListener(this);
        listView.setGroupIndicator(null);


        // 设置对文本内容变化的监听
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String content = s.toString().trim();
                searchMalls.clear();
                if (TextUtils.isEmpty(content)) {
                    mAdapter.addMalls(expandableModels);
                    mAdapter.notifyDataSetChanged();
                } else {
                    for (ExpandableModel expandableModel : expandableModels) {
                        ArrayList<MallModel> searchModel = new ArrayList<MallModel>();
                        for (MallModel mallModel : expandableModel.getMallModels()) {
                            if (mallModel.getMallName().contains(content)) {
                                searchModel.add(mallModel);
                            }
                        }
                        if (searchModel.size() > 0) {
                            searchMalls.add(new ExpandableModel(expandableModel.getCityName(), searchModel));
                        }
                    }
                    mAdapter.addMalls(searchMalls);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 设置child点击事件
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {


                for (ExpandableModel e : NexdApplication.malls) {
                    for (int i = 0; i < e.getMallModels().size(); i++) {
                        if (e.getMallModels().get(i).isSelected()) {
                            e.getMallModels().get(i).setIsSelected(false);
                        }
                    }
                }

                MallModel mallModel = mAdapter.getChild(groupPosition, childPosition);

                if (mallModel.isSelected()) {
                    mallModel.setIsSelected(false);
                } else {
                    mallModel.setIsSelected(true);
                }
                NexdApplication.selectedMallModel = mallModel;
                mAdapter.notifyDataSetChanged();
                return false;
            }
        });
        return view;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MobclickAgent.openActivityDurationTrack(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MallListFragment"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this.getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    /**
     * here is very importance for indicator group
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        final ExpandableListView listView = (ExpandableListView) view;
        /**
         * calculate point (0,0)
         */
        int npos = view.pointToPosition(0, 0);// 其实就是firstVisibleItem
        if (npos == AdapterView.INVALID_POSITION)// 如果第一个位置值无效
            return;

        long pos = listView.getExpandableListPosition(npos);
        int childPos = ExpandableListView.getPackedPositionChild(pos);// 获取第一行child的id
        int groupPos = ExpandableListView.getPackedPositionGroup(pos);// 获取第一行group的id
        if (childPos == AdapterView.INVALID_POSITION) {// 第一行不是显示child,就是group,此时没必要显示指示器
            View groupView = listView.getChildAt(npos
                    - listView.getFirstVisiblePosition());// 第一行的view
            indicatorGroupHeight = groupView.getHeight();// 获取group的高度
            indicatorGroup.setVisibility(View.GONE);// 隐藏指示器
        } else {
            indicatorGroup.setVisibility(View.VISIBLE);// 滚动到第一行是child，就显示指示器
        }
        // get an error data, so return now
        if (indicatorGroupHeight == 0) {
            return;
        }
        // update the data of indicator group view
        if (groupPos != indicatorGroupId) {// 如果指示器显示的不是当前group
            mAdapter.getGroupView(groupPos, listView.isGroupExpanded(groupPos),
                    indicatorGroup.getChildAt(0), null);// 将指示器更新为当前group
            indicatorGroupId = groupPos;
            Log.e(TAG, PRE + "bind to new group,group position = " + groupPos);
            // mAdapter.hideGroup(indicatorGroupId); // we set this group view
            // to be hided
            // 为此指示器增加点击事件
            indicatorGroup.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    listView.collapseGroup(indicatorGroupId);
                }
            });
        }
        if (indicatorGroupId == -1) // 如果此时grop的id无效，则返回
            return;

        /**
         * calculate point (0,indicatorGroupHeight) 下面是形成往上推出的效果
         */
        int showHeight = indicatorGroupHeight;
        int nEndPos = listView.pointToPosition(0, indicatorGroupHeight);// 第二个item的位置
        if (nEndPos == AdapterView.INVALID_POSITION)//如果无效直接返回
            return;
        long pos2 = listView.getExpandableListPosition(nEndPos);
        int groupPos2 = ExpandableListView.getPackedPositionGroup(pos2);//获取第二个group的id
        if (groupPos2 != indicatorGroupId) {//如果不等于指示器当前的group
            View viewNext = listView.getChildAt(nEndPos
                    - listView.getFirstVisiblePosition());
            showHeight = viewNext.getTop();
            Log.e(TAG, PRE + "update the show part height of indicator group:"
                    + showHeight);
        }

        // update group position
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) indicatorGroup
                .getLayoutParams();
        layoutParams.topMargin = -(indicatorGroupHeight - showHeight);
        indicatorGroup.setLayoutParams(layoutParams);
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

}

